package io.renren.modules.sp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RenException;
import io.renren.common.utils.JPAUtil;
import io.renren.modules.sp.dao.*;
import io.renren.modules.sp.dto.SpCertificateImport;
import io.renren.modules.sp.dto.SpMatchItemTeamImport;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.excel.SpSignRecordExcel;
import io.renren.modules.sp.service.SpMatchItemImportService;
import io.renren.modules.sp.service.SpMatchItemTeamService;
import io.renren.modules.sys.entity.SysDictDataEntity;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 选手荣誉证书导入
 */
@Service
public class SpMatchItemImportServiceImpl implements SpMatchItemImportService {

    @Autowired
    private SpUserDao spUserDao;
    @Autowired
    private SpMatchItemTeamService spMatchItemTeamService;
    @Autowired
    private SpBaseMatchItemDao spBaseMatchItemDao;
    @Autowired
    private SpCertificateImportDao spCertificateImportDao;
    @Autowired
    private SpMatchItemTeamUserDao spMatchItemTeamUserDao;
    @Autowired
    private SpMatchItemTeamDao spMatchItemTeamDao;
    @Autowired
    private SpMatchDao spMatchDao;

    /**
     * 导入成绩
     * task2023061
     * */
    public void importScore(List<SpMatchItemTeamImport> list, String matchId){
        for(SpMatchItemTeamImport itemImport :list ){
            initImportPormotion(itemImport,"score", matchId);
        }
        //导入
        for(SpMatchItemTeamImport itemImport :list ){
            if(StringUtils.isNotBlank(itemImport.getErrorMsg())){
                continue;
            }
            confirmImportScore(itemImport);
        }
    }
    /**
     * 导入晋级
     * */
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public String importPormotion(List<SpMatchItemTeamImport> list, String matchId){
        for(SpMatchItemTeamImport itemImport :list ){
            initImportPormotion(itemImport,"pormotion", matchId);
        }
        //保存error
        for(SpMatchItemTeamImport itemImport :list ){
            if(StringUtils.isNotBlank(itemImport.getErrorMsg())){
                return itemImport.getErrorMsg();
            }
        }
        //导入
        for(SpMatchItemTeamImport itemImport :list ){
            if(StringUtils.isNotBlank(itemImport.getErrorMsg())){
                continue;
            }
            confirmImportPromotion(itemImport);
        }
        return "";
    }

    /**
     * 确认导入
     */
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public void confirmImportPromotion(SpMatchItemTeamImport importDto ){

        //查询个人的报名记录
        SpMatchItemTeamUserEntity haveRecord = JPAUtil.selectById(SpMatchItemTeamUserEntity.class,
                JPAUtil.eq("user_id",importDto.getUserId()).eq("team_id",importDto.getTeamId())
                        .apply("  match_item_team_id  in (select t2.id from sp_match_item_team t2" +
                                " where t2.match_item_id = "  +importDto.getMatchItemId()+" " +
                                " and t2.team_id = "+importDto.getTeamId()+" and t2.status not in (3,7) )  "));
        //是否把数据入库，测试时候可以设置为false
        final boolean isSaveData = true;
        //晋级赛插入数据
        //生成赛赛报名表
        SpMatchItemTeamEntity matchItemTeamEntity =  new SpMatchItemTeamEntity();
        matchItemTeamEntity.setTeamName(importDto.getTeamName());
        matchItemTeamEntity.setTeamId(importDto.getTeamId());
        matchItemTeamEntity.setSignTime(new Date());
        //1报名成功  9待确认
        matchItemTeamEntity.setStatus(9);
        matchItemTeamEntity.setIsRise(0);
        matchItemTeamEntity.setTeamName(importDto.getTeamName());
        matchItemTeamEntity.setGroupId(importDto.getGroupId().intValue());
        matchItemTeamEntity.setMatchItemId(importDto.getMatchItemPid().intValue());
        //保存参赛记录
        if(isSaveData){
            JPAUtil.save(matchItemTeamEntity);
        }
        for(SpUserEntity userEntity : importDto.getUserList()){
            SpMatchItemTeamUserEntity user = new SpMatchItemTeamUserEntity();
            String msg =spMatchItemTeamService.checkOtherGroup(userEntity.getId(),importDto.getGroupId(),importDto.getMatchPid());
           if(StringUtils.isNotBlank(msg)){
               msg = userEntity.getRealName()+"已参加"+msg+"组别比赛，不能参加此组别比赛";
               importDto.setErrorMsg(msg);
               //学员参加了别的小组，把group删掉
               if(isSaveData){
                   spMatchItemTeamService.deleteById(matchItemTeamEntity.getId());
               }
               throw new RenException("msg");
           }
            msg = spMatchItemTeamService.checkMatchNumw(userEntity.getId(),importDto.getMatchPid(),
                    importDto.getMatchItemPid());
            if(StringUtils.isNotBlank(msg)){
                msg=userEntity.getRealName()+msg;
                importDto.setErrorMsg(msg);
                //学员有重复报名的情况，把group删掉
                if(isSaveData){
                    spMatchItemTeamService.deleteById(matchItemTeamEntity.getId());
                }
                throw new RenException("msg");
            }
            user.setStatus(9);
            user.setMatchItemTeamId(matchItemTeamEntity.getId());
            user.setTeamId(importDto.getTeamId());
            user.setUserId(userEntity.getId());
            user.setCreateDate(new Date());
            // 1选手
            user.setType(1);
            if(isSaveData){
                JPAUtil.save(user);
            }
        }
        for(SpUserEntity teacherEntity : importDto.getTeacherList()){
            SpMatchItemTeamUserEntity teacher = new SpMatchItemTeamUserEntity();
            teacher.setStatus(1);
            teacher.setMatchItemTeamId(matchItemTeamEntity.getId());
            teacher.setTeamId(importDto.getTeamId());
            teacher.setUserId(teacherEntity.getId());
            teacher.setCreateDate(new Date());
            // 2老师
            teacher.setType(2);
            if(isSaveData){
                JPAUtil.save(teacher);
            }
        }
    }
    /**
     *检查用户是否属于本队的
    */
    public String checkUserTeam(SpTeamEntity team ,SpUserEntity userEntity,String userName){
        SpTeamUserEntity teamUser = JPAUtil.selectById(SpTeamUserEntity.class,
                JPAUtil.eq("team_id",team.getId())
                        .eq("user_id",userEntity.getId()));
        if(teamUser ==null ){
            return userEntity.getRealName()+"不属于此代表队";
        }
        if(userName==null){
            return "姓名不能为空";
        }
        if(!userName.equals(userEntity.getRealName())){
            return "身份证和姓名不一致";
        }
        return null;
    }
    /**
     * 确认导入
     */
    public void confirmImportScore(SpMatchItemTeamImport importDto ){
        //查询个人的报名记录
        SpMatchItemTeamUserEntity haveRecord = JPAUtil.selectById(SpMatchItemTeamUserEntity.class,
                JPAUtil.eq("user_id",importDto.getUserList().get(0).getId()).eq("team_id",importDto.getTeamId())
                        .apply("  match_item_team_id  in (select t2.id from sp_match_item_team t2" +
                                " where t2.match_item_id = "  +importDto.getMatchItemId()+" " +
                                " and t2.team_id = "+importDto.getTeamId()+" and t2.status not in (3,7) )  "));

        if(haveRecord ==null){
            //生成赛赛报名表
            SpMatchItemTeamEntity matchItemTeamEntity =  new SpMatchItemTeamEntity();
            matchItemTeamEntity.setTeamName(importDto.getTeamName());
            matchItemTeamEntity.setTeamId(importDto.getTeamId());
            matchItemTeamEntity.setMatchItemId(importDto.getMatchItemId().intValue());
            matchItemTeamEntity.setGroupId(importDto.getGroupId().intValue());
            matchItemTeamEntity.setSignTime(new Date());
            //6已晋级
            matchItemTeamEntity.setStatus(6);
            matchItemTeamEntity.setIsRise(1);
            matchItemTeamEntity.setTeamName(importDto.getTeamName());
            matchItemTeamEntity.setGroupId(importDto.getGroupId().intValue());
            matchItemTeamEntity.setMatchItemId(importDto.getMatchItemId().intValue());
            matchItemTeamEntity.setRiseTime(new Date());
            //保存参赛记录
            JPAUtil.save(matchItemTeamEntity);
            for(SpUserEntity userEntity : importDto.getUserList()){
                SpMatchItemTeamUserEntity user = new SpMatchItemTeamUserEntity();
                user.setStatus(1);
                user.setMatchItemTeamId(matchItemTeamEntity.getId());
                user.setTeamId(importDto.getTeamId());
                user.setUserId(userEntity.getId());
                user.setCreateDate(new Date());
                user.setType(1);
                JPAUtil.save(user);
            }
            for(SpUserEntity teacherEntity : importDto.getUserList()){
                SpMatchItemTeamUserEntity teacher = new SpMatchItemTeamUserEntity();
                teacher.setStatus(1);
                teacher.setMatchItemTeamId(matchItemTeamEntity.getId());
                teacher.setTeamId(importDto.getTeamId());
                teacher.setUserId(teacherEntity.getId());
                teacher.setCreateDate(new Date());
                teacher.setType(2);
                JPAUtil.save(teacher);
            }
        }
        //查询并修改成绩
        for(SpUserEntity userEntity : importDto.getUserList()){
            //查询个人的报名记录
            SpMatchItemTeamUserEntity itemRecores = JPAUtil.selectById(SpMatchItemTeamUserEntity.class,
                    JPAUtil.eq("user_id",importDto.getUserList().get(0).getId()).eq("team_id",importDto.getTeamId())
                            .apply("  match_item_team_id  in (select t2.id from sp_match_item_team t2" +
                                    " where t2.match_item_id = "  +importDto.getMatchItemId()+" " +
                                    " and t2.team_id = "+importDto.getTeamId()+" and t2.status not in (3,7) )  "));
            if(itemRecores !=null ){
                itemRecores.setScore(importDto.getScore());
                itemRecores.setCertificate(importDto.getCertificate());
                itemRecores.setGroupRank(importDto.getRank());
                JPAUtil.update(itemRecores);
            }
        }
    }

    /**
     * 导入晋级校验
     *
     * @param importDto
     * @param type
     */
    public void initImportPormotion(SpMatchItemTeamImport importDto, String type, String matchId){
        SpMatchEntity matchEntity = JPAUtil.selectById(SpMatchEntity.class,JPAUtil.eq("id",matchId));
        //2基础赛项
        SpBaseMatchItemEntity baseMatchItem = JPAUtil.selectById(SpBaseMatchItemEntity.class,JPAUtil.eq("item_name",importDto.getBaseMatchItemName()));
        if (baseMatchItem ==null){
            importDto.setErrorMsg("未查到"+"基础赛项");
            return;
        }
        //3查询赛项
        SpMatchItemEntity matchItemEntity = JPAUtil.selectById(
                SpMatchItemEntity.class,
                JPAUtil.eq("match_id",matchEntity.getId())
                        .eq("base_match_item_id",baseMatchItem.getId())
        );
        if (matchItemEntity ==null){
            importDto.setErrorMsg("未查到"+"基础赛项");
            return;
        }
        //4查询代表队
        //根据手机号查询用户
        SpUserEntity createUser = JPAUtil.selectById(SpUserEntity.class,JPAUtil.eq("phone",importDto.getTeamPhone()));
        if(createUser ==null){
            importDto.setErrorMsg("根据手机号未查到"+"代表队负责人");
            return;
        }
        SpTeamEntity team = JPAUtil.selectById(SpTeamEntity.class,JPAUtil.eq("creator",createUser.getId()));
        if (team ==null){
            importDto.setErrorMsg("根据手机号未查到"+"代表队");
            return;
        }
        SysDictDataEntity groupEntity = JPAUtil.selectById(SysDictDataEntity.class,
                JPAUtil.eq("dict_type_id",100300L)
                        .eq("dict_label",importDto.getGroupName()));
        //5查询组别
        if (groupEntity ==null){
            importDto.setErrorMsg("未查到"+"组别");
            return;
        }
        SpMatchEntity matchEntityParent=null;
        SpMatchItemEntity matchItemParent =null;
        if("pormotion".equals(type)){
            //6查询赛事
             matchEntityParent =JPAUtil.selectById(SpMatchEntity.class,matchEntity.getMatchParentId().longValue());
            if (matchEntityParent ==null){
                importDto.setErrorMsg("未查到"+"晋级赛事");
                return;
            }
            //7查询赛项
            matchItemParent = JPAUtil.selectById(
                    SpMatchItemEntity.class,
                    JPAUtil.eq("match_id",matchEntityParent.getId())
                            .eq("base_match_item_id",baseMatchItem.getId())
            );
            if (matchItemParent ==null){
                importDto.setErrorMsg("未查到"+"晋级赛事的赛项");
                return;
            };
            importDto.setMatchPid(matchEntityParent.getId());
            importDto.setMatchItemPid(matchItemParent.getId());
        }
        if(StringUtils.isNotBlank(importDto.getUserCard())){
            //5查询选手
            SpUserEntity  user =JPAUtil.selectById(SpUserEntity.class,
                    JPAUtil.eq("id_card",importDto.getUserCard())
                            .eq("real_name", importDto.getUser())
                            .like("role_id", "3"));
            if (user ==null){
                importDto.setErrorMsg("未查到"+"选手");
                return;
            }
            // 校验选手是否属于当前代表队
            String checkMsg =  checkUserTeam(team,user,importDto.getUser());
            if(StringUtils.isNotBlank(checkMsg)){
                importDto.setErrorMsg("选手："+checkMsg);
                return;
            }
           SpUserEntity  teacher =JPAUtil.selectById(SpUserEntity.class,
                   JPAUtil.eq("id_card",importDto.getTeacherCard())
                           .eq("real_name", importDto.getTeacher())
                           .like("role_id", "2"));
            if (teacher ==null&&"pormotion".equals(type)){
                    importDto.setErrorMsg("未查到"+"老师");
                    return;
             }
            List<SpUserEntity> userList = new ArrayList<>(5);
            List<SpUserEntity> teacherList = new ArrayList<>();
            userList.add(user);
            if(teacher !=null){
                teacherList.add(teacher);
                importDto.setTeacherId(teacher.getId());
                // 校验老师是否属于当前代表队
                String checkMsg2 =  checkUserTeam(team,teacher,importDto.getTeacher());
                if(StringUtils.isNotBlank(checkMsg2)){
                    importDto.setErrorMsg("指导老师："+checkMsg2);
                    return;
                }
            }
            importDto.setUserId(user.getId().longValue());

            importDto.setUserList(userList);
            importDto.setTeacherList(teacherList);
        }else{
            List<SpUserEntity> userList = new ArrayList<>(5);
            if(StringUtils.isBlank(importDto.getTeamName())){
                importDto.setErrorMsg("队伍名称不能为空");
                return;
            }
            if(StringUtils.isNotBlank(importDto.getUser1Card())){
                SpUserEntity  user1 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getUser1Card())
                                .eq("real_name", importDto.getUser1()).like("role_id", "3"));
                if(user1 ==null){
                    importDto.setErrorMsg("未查到"+"选手1");
                    return;
                }
                userList.add(user1);
                String checkMsg =  checkUserTeam(team,user1,importDto.getUser1());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("选手1："+checkMsg);
                    return;
                }
            }
            if(StringUtils.isNotBlank(importDto.getUser2Card())){
                SpUserEntity user2 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getUser2Card())
                                .eq("real_name", importDto.getUser2()).like("role_id", "3"));
                if(user2 ==null){
                    importDto.setErrorMsg("未查到"+"选手2");
                    return;
                }
                userList.add(user2);
                String checkMsg =  checkUserTeam(team,user2,importDto.getUser2());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("选手2："+checkMsg);
                    return;
                }
            }
            if(StringUtils.isNotBlank(importDto.getUser3Card())){
                SpUserEntity  user3 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getUser3Card())
                                .eq("real_name", importDto.getUser3()).like("role_id", "3"));
                if(user3 ==null){
                    importDto.setErrorMsg("未查到"+"选手3");
                    return;
                }
                userList.add(user3);
                String checkMsg =  checkUserTeam(team,user3,importDto.getUser3());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("选手3："+checkMsg);
                    return;
                }
            }
            if(StringUtils.isNotBlank(importDto.getUser4Card())){
                SpUserEntity  user4 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getUser4Card())
                                .eq("real_name", importDto.getUser4()).like("role_id", "3"));
                if(user4 ==null){
                    importDto.setErrorMsg("未查到"+"选手4");
                    return;
                }
                userList.add(user4);
                String checkMsg =  checkUserTeam(team,user4,importDto.getUser4());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("选手4："+checkMsg);
                    return;
                }
            }
            if(StringUtils.isNotBlank(importDto.getUser5Card())){
                SpUserEntity  user5 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getUser5Card())
                                .eq("real_name", importDto.getUser5()).like("role_id", "3"));
                if(user5 ==null){
                    importDto.setErrorMsg("未查到"+"选手5");
                    return;
                }
                userList.add(user5);
                String checkMsg =  checkUserTeam(team,user5,importDto.getUser5());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("选手5："+checkMsg);
                    return;
                }
            }
            if(StringUtils.isNotBlank(importDto.getUser6Card())){
                SpUserEntity  user6 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getUser6Card())
                                .eq("real_name", importDto.getUser6()).like("role_id", "3"));
                if(user6 ==null){
                    importDto.setErrorMsg("未查到"+"选手6");
                    return;
                }
                userList.add(user6);
                String checkMsg =  checkUserTeam(team,user6,importDto.getUser6());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("选手6："+checkMsg);
                    return;
                }
            }
            List<SpUserEntity> teacherList = new ArrayList<>();
            if(StringUtils.isNotBlank(importDto.getTeacher1Card())) {
                SpUserEntity teacher1 = JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card", importDto.getTeacher1Card())
                                .eq("real_name", importDto.getTeacher1()).like("role_id", "2"));
                if (teacher1 == null) {
                    importDto.setErrorMsg("未查到" + "指导老师1");
                    return;
                }
                teacherList.add(teacher1);
                String checkMsg = checkUserTeam(team, teacher1, importDto.getTeacher1());
                if (StringUtils.isNotBlank(checkMsg)) {
                    importDto.setErrorMsg("指导老师1：" + checkMsg);
                    return;
                }
            }
            if(StringUtils.isNotBlank(importDto.getTeacher2Card())){
                SpUserEntity  teacher2 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getTeacher2Card())
                                .eq("real_name", importDto.getTeacher2()).like("role_id", "2"));
                if (teacher2 == null) {
                    importDto.setErrorMsg("未查到" + "指导老师2");
                    return;
                }
                teacherList.add(teacher2);
                String checkMsg =  checkUserTeam(team,teacher2,importDto.getTeacher2());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("指导老师2："+checkMsg);
                    return;
                }
            }
            if(StringUtils.isNotBlank(importDto.getTeacher3Card())){
                SpUserEntity  teacher3 =JPAUtil.selectById(SpUserEntity.class,
                        JPAUtil.eq("id_card",importDto.getTeacher3Card())
                                .eq("real_name", importDto.getTeacher3()).like("role_id", "2"));
                if (teacher3 == null) {
                    importDto.setErrorMsg("未查到" + "指导老师3");
                    return;
                }
                teacherList.add(teacher3);
                String checkMsg =  checkUserTeam(team,teacher3,importDto.getTeacher3());
                if(StringUtils.isNotBlank(checkMsg)){
                    importDto.setErrorMsg("指导老师3："+checkMsg);
                    return;
                }
            }
            importDto.setUserList(userList);
            importDto.setTeacherList(teacherList);
            matchItemParent.getStudentNum();
            if(userList.size() <matchItemParent.getStudentNum() || userList.size() > matchItemParent.getStudentNumMax()){
                importDto.setErrorMsg(String.format("选手应该为%s~%s名",matchItemParent.getStudentNum(),matchItemParent.getStudentNumMax()));
                return;
            }
            if(teacherList.size() <matchItemParent.getTeacherNum() || teacherList.size() > matchItemParent.getTeacherNumMax()){
                importDto.setErrorMsg(String.format("指导老师应该为%s~%s名",matchItemParent.getTeacherNum(),matchItemParent.getTeacherNumMax()));
                return;
            }
        }
        importDto.setTeamId(team.getId());
        importDto.setMatchId(matchEntity.getId());
        importDto.setMatchItemId(matchItemEntity.getId());
        importDto.setGroupId(groupEntity.getId());
    }

    /**
     * 导入获奖证书校验
     * @param spCertificateImport
     */
    @Override
    public SpCertificateImport checkCertificate(SpCertificateImport spCertificateImport){
        // 校验赛事名称是否存在
        SpMatchEntity spMatchEntity = spMatchDao.selectOne(
                new QueryWrapper<SpMatchEntity>()
                        .eq("match_name",spCertificateImport.getMatchName())
        );
        if(spMatchEntity == null){
            spCertificateImport.setCheckMsg("赛事名称不存在");
            return spCertificateImport;
        }

        // 校验手机号和身份证不能同时为空
        if(StringUtils.isBlank(spCertificateImport.getPhone()) && StringUtils.isBlank(spCertificateImport.getIdCard())){
            spCertificateImport.setCheckMsg("手机号和身份证不能同时为空");
            return spCertificateImport;
        }
        // 如果手机号不为空根据手机号校验是否存在当前用户
        if(StringUtils.isNotBlank(spCertificateImport.getPhone())){
            SpUserEntity user = spUserDao.selectOne(new QueryWrapper<SpUserEntity>().eq("phone",spCertificateImport.getPhone()));
            if(user == null){
                //手机号不存在，再校验身份证
                SpUserEntity userIdCard = spUserDao.selectOne(new QueryWrapper<SpUserEntity>().eq("id_card",spCertificateImport.getIdCard()));
                if(userIdCard == null) {
                    spCertificateImport.setCheckMsg("手机号和身份证不存在");
                    return spCertificateImport;
                }else{
                    //匹配身份证号与姓名是否一致
                    if(!userIdCard.getRealName().equals(spCertificateImport.getUserName())){
                        spCertificateImport.setCheckMsg("身份证和姓名不匹配");
                        return spCertificateImport;
                    }
                }
            }else{
                if(!user.getRealName().equals(spCertificateImport.getUserName())){
                    spCertificateImport.setCheckMsg("手机号和姓名不匹配");
                    return spCertificateImport;
                }else{
                    spCertificateImport.setUserId(user.getId());
                }
                //手机号不匹配，再校验身份证
                SpUserEntity userIdCard = spUserDao.selectOne(new QueryWrapper<SpUserEntity>().eq("id_card",spCertificateImport.getIdCard()));
                if(userIdCard == null) {
                    spCertificateImport.setCheckMsg("身份证不存在");
                    return spCertificateImport;
                }else{
                    //匹配身份证号与姓名是否一致
                    if(!userIdCard.getRealName().equals(spCertificateImport.getUserName())){
                        spCertificateImport.setCheckMsg("身份证和姓名不匹配");
                        return spCertificateImport;
                    }else {
                        spCertificateImport.setUserId(userIdCard.getId());
                    }
                }
            }
        }else{
            // 如果手机号为空根据身份证校验是否存在当前用户
            List<SpUserEntity> userList = spUserDao.selectList(new QueryWrapper<SpUserEntity>().eq("id_card",spCertificateImport.getIdCard()));
            if(userList == null || userList.size()==0){
                spCertificateImport.setCheckMsg("身份证不存在");
                return spCertificateImport;
            }else if(userList.size()>1){
                spCertificateImport.setCheckMsg(spCertificateImport.getIdCard()+"身份证重复");
                return spCertificateImport;
            } else {
                SpUserEntity user = userList.get(0);
                if(!user.getRealName().equals(spCertificateImport.getUserName())){
                    spCertificateImport.setCheckMsg("身份证和姓名不匹配");
                    return spCertificateImport;
                }
                spCertificateImport.setUserId(user.getId());
            }
        }
        // 校验赛项名称是否存在
        SpBaseMatchItemEntity spBaseMatchItemEntity = spBaseMatchItemDao.selectOne(
                new QueryWrapper<SpBaseMatchItemEntity>()
                        .eq("item_name",spCertificateImport.getBaseMatchItemName())
        );
        if(spBaseMatchItemEntity == null){
            spCertificateImport.setCheckMsg("基础赛项名称不存在");
            return spCertificateImport;
        }
        // 校验证书编号是否和库内重复
        List<SpCertificateImportEntity> certificateList = this.spCertificateImportDao.selectList(
                new QueryWrapper<SpCertificateImportEntity>()
                        .eq("certificate",spCertificateImport.getCertificate())
        );
        if(certificateList!=null && certificateList.size()>0){
            spCertificateImport.setCheckMsg( spCertificateImport.getCertificate() + "证书编号重复");
            return spCertificateImport;
        }
        return spCertificateImport;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCertificateImport(List<SpCertificateImport> spCertificateImport){
        SpCertificateImportEntity spCertificateEntity = null;
         for (SpCertificateImport importDto : spCertificateImport) {
             spCertificateEntity = new SpCertificateImportEntity();
             BeanUtils.copyProperties(importDto, spCertificateEntity);
             spCertificateImportDao.insert(spCertificateEntity);
         }
    }

    /**
     * 导入校验
     * @param excel
     */
    @Override
    public void checkMatchScore(SpSignRecordExcel excel, int matchItemId){
        //校验表头是否一致： 序号、代表队、选手、选手编号、学校/单位
        if(StringUtils.isEmpty(excel.getId()) || StringUtils.isEmpty(excel.getTeamName())
                || StringUtils.isEmpty(excel.getRealName())   // || StringUtils.isEmpty(excel.getTicket())
                || StringUtils.isEmpty(excel.getCompany())){
            excel.setCheckMsg("表头不一致");
        }

        //校验序号和学生一致
        boolean isGroup = false;
        String realName = excel.getRealName();
        if(realName!=null && realName.contains("、")){
            isGroup = true;
        }
        //个人赛
        if(!isGroup){
            SpMatchItemTeamUserEntity entity = spMatchItemTeamUserDao.selectById(excel.getId());
            if(entity == null) {
                excel.setCheckMsg("序号不存在");
            }else{
                SpUserEntity user = spUserDao.selectById(entity.getUserId());
                if(!user.getRealName().equals(excel.getRealName())){
                    excel.setCheckMsg("序号和学生不一致");
                }
            }
            //判断国赛是否已经开始 --二期开发
            this.checkMatchItem(excel, matchItemId,"1");
        }else {
            //团体赛
            List<SpMatchItemTeamUserEntity> userList = spMatchItemTeamUserDao.selectList(new QueryWrapper<SpMatchItemTeamUserEntity>()
                    .eq("match_item_team_id",excel.getId())
                    .eq("type","1")
            );
            //判断realName 与 userList 中的学生姓名是否一致
            String[] realNameArr = realName.split("、");
            if(realNameArr.length != userList.size()){
                excel.setCheckMsg("序号和学生不一致");
            }else{
                if(userList != null && userList.size()>0){
                    for (SpMatchItemTeamUserEntity userEntity : userList) {
                        SpUserEntity user = spUserDao.selectById(userEntity.getUserId());
                        if(!realName.contains(user.getRealName())){
                            excel.setCheckMsg("序号和学生不一致");
                        }
                    }
                }
            }
        }

        if(StringUtils.isEmpty(excel.getScore1()) && StringUtils.isEmpty(excel.getScore2()) && StringUtils.isEmpty(excel.getScore())){
            excel.setCheckMsg("维度一、维度二、维度三不能同时为空");
        }

        // 新增名次校验
        if (StringUtils.isNotEmpty(excel.getRanks())) {
            if (!excel.getRanks().matches("^[1-9]\\d*$")) {
                excel.setCheckMsg("名次必须为正整数或为空");
            }
        }

        //判断国赛是否已经开始 --二期开发
        //this.checkMatchItem(excel, matchItemId, "2");

        // ④团体类的比赛，同group的名次是同样的数字
        // todo

        //⑤ 导入后按照名次排序
        // todo
    }

    /**
     * 校验是否是同一场赛项
     * @param excel
     * @param matchItemId
     * @param type 1个人赛/2团体赛
     */
    public void checkMatchItem(SpSignRecordExcel excel, int matchItemId, String type){
        //判断国赛是否已经开始 --二期开发
        Map<String,Object> matchEntity = spMatchItemTeamUserDao.queryMatchInfo(excel.getId());
        if("1".equals(type)) {
            matchEntity = spMatchItemTeamUserDao.queryMatchInfo(excel.getId());
        }else{
            matchEntity = spMatchItemTeamUserDao.queryMatchInfoByTeam(excel.getId());
        }
        if(matchEntity!=null) {
            Integer matchLevel = (Integer) matchEntity.get("match_level");
            Integer matchParentId = (Integer) matchEntity.get("match_parent_id");
            Long mid = (Long) matchEntity.get("matchItemId");
            // 校验是否同一场赛项
            if(mid.intValue() != matchItemId){
                excel.setCheckMsg("不是同一场赛项");
            }
            // 如果是省赛，且存在母赛事
            /*if (matchEntity != null && matchLevel == 2 && matchParentId != null) {
                SpMatchEntity parentMatch = spMatchDao.selectById(matchParentId);
                //判断是否开始
                if (parentMatch.getEndSignup().getTime() < (new Date()).getTime()) {
                    excel.setCheckMsg("国赛报名已经截止，不能导入成绩");
                }
            }*/
        }
    }

    @Override
    public void importMatchScore(SpSignRecordExcel excel){
        // 判断是否团体赛
        boolean isGroup = false;
        String realName = excel.getRealName();
        if(realName.contains("、")){
            isGroup = true;
        }
        //个人赛
        if(!isGroup) {
            SpMatchItemTeamUserEntity entity = spMatchItemTeamUserDao.selectById(excel.getId());
            entity.setId(Long.parseLong(excel.getId()));
            //打分工具的不导入成绩
            if(!"1".equals(entity.getIsAutoScore())) {
                entity.setScore(excel.getScore());
                entity.setScore1(excel.getScore1());
                entity.setScore2(excel.getScore2());
            }
            entity.setGrade(excel.getGrade());
            entity.setRemark(excel.getRemark());
            spMatchItemTeamUserDao.updateById(entity);
            if(StringUtils.isNotEmpty(excel.getRanks()) && !"null".equals(excel.getRanks())){
                SpMatchItemTeamEntity mitEntity = spMatchItemTeamDao.selectById(entity.getMatchItemTeamId());
                mitEntity.setRanks(Integer.parseInt(excel.getRanks()));
                spMatchItemTeamDao.updateById(mitEntity);
            }
        }else{
            //团体赛
            spMatchItemTeamUserDao.selectList(new QueryWrapper<SpMatchItemTeamUserEntity>()
                    .eq("match_item_team_id",excel.getId())
                    .eq("type","1")
            ).forEach(userEntity -> {
                //打分工具的不导入成绩
                if(!"1".equals(userEntity.getIsAutoScore())) {
                    userEntity.setScore(excel.getScore());
                    userEntity.setScore1(excel.getScore1());
                    userEntity.setScore2(excel.getScore2());
                }
                userEntity.setGrade(excel.getGrade());
                userEntity.setRemark(excel.getRemark());
                spMatchItemTeamUserDao.updateById(userEntity);
            });
            if(StringUtils.isNotEmpty(excel.getRanks()) && !"null".equals(excel.getRanks())){
                SpMatchItemTeamEntity mitEntity = spMatchItemTeamDao.selectById(excel.getId());
                mitEntity.setRanks(Integer.parseInt(excel.getRanks()));
                spMatchItemTeamDao.updateById(mitEntity);
            }
        }
    }
}
